package cn.bas;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @Configuration
    public class RestTemplateConfiguraion{
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }

    @RestController
    static class TestController{
        @Autowired
        private DiscoveryClient discoveryClient;
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/hello")
        public String hello(String name){
            ServiceInstance serviceInstance;
            if(true){
                List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");
                serviceInstance = instances.size()>0?instances.get(0): null;
            }else{
                serviceInstance = loadBalancerClient.choose("demo-provider");
            }
            if(serviceInstance==null){
                throw new IllegalStateException("找不到实例");
            }
            String targetUri = serviceInstance.getUri()+"/echo?name="+name;
            String response = restTemplate.getForObject(targetUri,String.class);

            return "consumer:"+response;
        }

    }
}